package city.spring.modules.medicine.controller;

import city.spring.modules.medicine.entity.MedicineEntity;
import city.spring.modules.medicine.service.MedicineService;
import city.spring.modules.medicine.service.MedicineshelflevelService;
import city.spring.modules.medicine.service.MedicinestorehouseService;
import city.spring.modules.medicine.vo.MedicineVO;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.data.web.SortDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Controller：药品信息
 *
 * @author 谢金婷
 * @date 2020-06-19 10:08:21
 */
@RestController
@RequestMapping("/medicine")
public class MedicineController extends ApiController {
    private final MedicineService medicineService;
    private final MedicinestorehouseService storehouseService;
    private final MedicineshelflevelService shelflevelService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MedicineEntity, ?>> entityOrderFields;

    public MedicineController(MedicineService medicineService, MedicinestorehouseService storehouseService, MedicineshelflevelService shelflevelService) {
        this.medicineService = medicineService;
        this.storehouseService = storehouseService;
        this.shelflevelService = shelflevelService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MedicineEntity::getId);
        entityOrderFields.add(MedicineEntity::getName);
        entityOrderFields.add(MedicineEntity::getCategory);
        entityOrderFields.add(MedicineEntity::getSpecifications);
        entityOrderFields.add(MedicineEntity::getUnit);
        entityOrderFields.add(MedicineEntity::getUnitprice);
        entityOrderFields.add(MedicineEntity::getDosageunit);
        entityOrderFields.add(MedicineEntity::getType);
        entityOrderFields.add(MedicineEntity::getDescription);
        entityOrderFields.add(MedicineEntity::getGmtCreate);
        entityOrderFields.add(MedicineEntity::getGmtModified);
        entityOrderFields.add(MedicineEntity::getProductiondate);
        entityOrderFields.add(MedicineEntity::getExpirationdate);
    }

    /**
     * 获取全部的 <strong>药品信息</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault(sort = {"gmtCreate"}) Pageable pageable, MedicineEntity entity) {
        LambdaQueryChainWrapper<MedicineEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>药品信息</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "category", direction = Sort.Direction.ASC), @SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicineVO entity) {

        QueryWrapper<? extends MedicineEntity> queryWrapper = buildQuery(entity);
        return success(medicineService.listPage(MyBatisUtils.toPage(pageable), queryWrapper));

//        LambdaQueryChainWrapper<MedicineEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MedicineEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        for (MedicineEntity record : page.getRecords()) {
//            try {
//                MedicinestorehouseEntity storehouseEntity = storehouseService.getById(record.getStorehouseId());
//                record.setSname(storehouseEntity.getSname());
//            } catch (Exception ignore) {
//                record.setStorehouseId(null);
//                record.setSname("< 找不到仓库 >");
//            }
//        }
//        for (MedicineEntity record : page.getRecords()) {
//            try {
//                MedicineshelflevelEntity shelflevelEntity = shelflevelService.getById(record.getShelfId());
//                record.setShelflevelname(shelflevelEntity.getSname());
//            } catch (Exception ignore) {
//                record.setShelfId(null);
//                record.setShelflevelname("< 找不到货架 >");
//            }
//        }
//        return success(page);
    }

    @GetMapping("/getMedicineIswarehousingPage")
    public Object getMedicineIswarehousingPage(@PageableDefault @SortDefault.SortDefaults({@SortDefault(sort = "category", direction = Sort.Direction.ASC), @SortDefault(sort = "id", direction = Sort.Direction.DESC)}) Pageable pageable, MedicineVO entity) {

        QueryWrapper<? extends MedicineEntity> queryWrapper = getMedicineIswarehousingPage(entity);
        return success(medicineService.getMedicineIswarehousingPage(MyBatisUtils.toPage(pageable), queryWrapper));
    }

    /**
     * 获取一个 <strong>药品信息</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {

        QueryWrapper<MedicineVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicineVO> records = medicineService.listPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(medicineService.getById(id));
    }

    @GetMapping("/getMedicineIswarehousing/{id}")
    public Object getMedicineIswarehousinginfo(@PathVariable String id) {

        QueryWrapper<MedicineVO> wrapper = new QueryWrapper<>();
        wrapper.eq("t1.id", id);
        List<MedicineVO> records = medicineService.getMedicineIswarehousingPage(new Page<>(), wrapper).getRecords();
        if (records.isEmpty()) {
            return success(null);
        }
        return success(records.get(0));

//        return success(medicineService.getById(id));
    }

    /**
     * 添加一个 <strong>药品信息</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody MedicineEntity entity) {
        medicineService.saveMedicine(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>药品信息</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody MedicineEntity entity) {
        entity.setId(id);
        medicineService.updateMedicine(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>药品信息</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        medicineService.deleteMedicine(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>药品信息</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        medicineService.deleteMedicine(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MedicineEntity> buildLambdaQuery(MedicineEntity entity) {
        LambdaQueryChainWrapper<MedicineEntity> lambdaQuery = medicineService.lambdaQuery();
        lambdaQuery.eq(entity.getId() != null, MedicineEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getName()), MedicineEntity::getName, entity.getName());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCode()), MedicineEntity::getCode, entity.getCode());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getCategory()), MedicineEntity::getCategory, entity.getCategory());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSpecifications()), MedicineEntity::getSpecifications, entity.getSpecifications());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getUnit()), MedicineEntity::getUnit, entity.getUnit());
        lambdaQuery.eq(entity.getUnitprice() != null, MedicineEntity::getUnitprice, entity.getUnitprice());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDosageunit()), MedicineEntity::getDosageunit, entity.getDosageunit());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getType()), MedicineEntity::getType, entity.getType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDescription()), MedicineEntity::getDescription, entity.getDescription());
        lambdaQuery.eq(entity.getGmtCreate() != null, MedicineEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, MedicineEntity::getGmtModified, entity.getGmtModified());
        lambdaQuery.eq(entity.getProductiondate() != null, MedicineEntity::getProductiondate, entity.getProductiondate());
        lambdaQuery.eq(entity.getExpirationdate() != null, MedicineEntity::getExpirationdate, entity.getExpirationdate());
        return lambdaQuery;
    }

//    /**
//     * 获取所有已入库药品
//     *
//     * @param pageable
//     * @return
//     */
//    @GetMapping("/getMedicineIswarehousing")
//    public Object getMedicineIswarehousing(Pageable pageable) {
//        return success(medicineService.getMedicineIswarehousing(pageable));
//    }

    /**
     * 获取所有未入库药品,分页展示
     *
     * @param pageable
     * @return
     */
    @GetMapping("/getMedicineNowarehousing")
    public Object getMedicineNowarehousing(Pageable pageable) {
        return success(medicineService.getMedicineNowarehousing(pageable));
    }

    /**
     * 获取所有的已入库药品信息，列表展示
     *
     * @return
     */
    @GetMapping("/getMedicineByIswarehousing")
    public Object getMedicineByIswarehousing() {
        return success(medicineService.getMedicineByIswarehousing());
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MedicineEntity> buildQuery(MedicineVO entity) {
        QueryWrapper<MedicineEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.eq(StringUtils.isNotBlank(entity.getSupplierId()), "t1.supplier_id", entity.getSupplierId());
        wrapper.like(StringUtils.isNotBlank(entity.getSuppliername()), "t2.suppliername", entity.getSuppliername());
        wrapper.like(StringUtils.isNotBlank(entity.getCategory()), "t1.category", entity.getCategory());
        return wrapper;
    }

    private QueryWrapper<MedicineEntity> getMedicineIswarehousingPage(MedicineVO entity) {
        QueryWrapper<MedicineEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(entity.getId() != null, "t1.id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getName()), "t1.name", entity.getName());
        wrapper.like(StringUtils.isNotBlank(entity.getCode()), "t1.code", entity.getCode());
        wrapper.eq(StringUtils.isNotBlank(entity.getSupplierId()), "t1.supplier_id", entity.getSupplierId());
        wrapper.like(StringUtils.isNotBlank(entity.getSuppliername()), "t2.suppliername", entity.getSuppliername());
        wrapper.like(StringUtils.isNotBlank(entity.getCategory()), "t1.category", entity.getCategory());
        return wrapper;
    }

}
